<template>
  <div id="app">
    <Add @add="handleAdd" />
    <hr />

    <List :rows="carts" @update="handleUpdate" @delete="handleDel" />
  </div>
</template>

<script>
import Add from "./components/Add.vue";
import List from "./components/List.vue";

// 引入 axios
import axios from "axios";

// 配置 axios.defaults.baseURL
axios.defaults.baseURL = "http://localhost:3000";

export default {
  components: {
    Add,
    List,
  },

  data() {
    return {
      carts: [], // 购物车数据
    };
  },

  methods: {
    async fetchData() {
      const response = await axios.get("/carts");
      // console.log(response, "===");
      // 将 response.data 赋值给 carts
      this.carts = response.data;
    },

    // 处理添加
    async handleAdd({ productName, price, count }) {
      await axios.post("/carts", {
        productName,
        price,
        count,
      });
      console.log("添加成功");
      this.fetchData();
    },

    // 处理删除
    async handleDel(id) {
      await axios.delete("/carts/" + id);
      this.fetchData();
    },

    async handleUpdate({ id, newCount }) {
      await axios.patch("/carts/" + id, {
        count: newCount,
      });
      this.fetchData();
    },
  },

  mounted() {
    // 默认获取数据一次
    this.fetchData();

    console.log(this.carts);
  },
};
</script>

<style>
#app {
  width: 600px;
  margin: 10px auto;
}

.tb {
  border-collapse: collapse;
  width: 100%;
}

.tb th {
  background-color: #0094ff;
  color: white;
}

.tb td,
.tb th {
  padding: 5px;
  border: 1px solid black;
  text-align: center;
}

.tb img {
  width: 100px;
  height: 100px;
}

.add {
  padding: 5px;
  border: 1px solid black;
  margin-bottom: 10px;
}

button:disabled {
  background-color: gray;
}
</style>
